package com.guoxin.concurrentprogramming.chapter2;

import java.util.concurrent.TimeUnit;

/**
 * @author guoxin
 * @date 2019/7/15
 */
public class SimpleWaitNotify {
    private static final Object LOCK = new Object();

    private static class WaitThread extends Thread {
        WaitThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            synchronized (LOCK) {
                System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " starting...");
                try {
                    System.out.println(System.currentTimeMillis() + " wait for Object ...");
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " ending...");
            }
        }
    }

    private static class NotifyThread extends Thread {

        NotifyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            synchronized (LOCK) {
                System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " starting...");
                LOCK.notify();
                System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " ending...");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new WaitThread("wait").start();
        new NotifyThread("notify").start();
    }
}
